
#include "stdafx.h"
#include "mimosav2client.h"
#include "mimosav2clientDlg.h"


#include "Wininet.h"
#define	NO_USE_HttpQueryInfo	1
#ifdef	NO_USE_HttpQueryInfo
#include <string>
using namespace std;
#endif

BOOL HttpRequest(char *pszURL, char *pszPostData, char **pszOutBuffer)
{
	char szScheme[INTERNET_MAX_SCHEME_LENGTH], szHostName[INTERNET_MAX_HOST_NAME_LENGTH],
		szUserName[INTERNET_MAX_USER_NAME_LENGTH], szPassword[INTERNET_MAX_PASSWORD_LENGTH],
		szUrlPath[INTERNET_MAX_PATH_LENGTH], szExtraInfo[INTERNET_MAX_PATH_LENGTH];
	URL_COMPONENTS urlComponents = {
		sizeof(URL_COMPONENTS),
		szScheme, INTERNET_MAX_SCHEME_LENGTH, INTERNET_SCHEME_DEFAULT,
		szHostName, INTERNET_MAX_HOST_NAME_LENGTH, 
		80,
		szUserName, INTERNET_MAX_USER_NAME_LENGTH,
		szPassword, INTERNET_MAX_PASSWORD_LENGTH,
		szUrlPath, INTERNET_MAX_PATH_LENGTH,
		szExtraInfo, INTERNET_MAX_PATH_LENGTH
	};
	if (FALSE == InternetCrackUrl(pszURL, lstrlen(pszURL), 0, &urlComponents))
	{
		return FALSE;
	}

	BOOL bRet = FALSE;

	HINTERNET hSession = InternetOpen("HTTPTEST", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession)
	{
		HINTERNET hConnect = InternetConnect(hSession,
			urlComponents.lpszHostName, urlComponents.nPort, urlComponents.lpszUserName, urlComponents.lpszPassword, urlComponents.nScheme, 0, 0);
		if (hConnect)
		{
			HINTERNET hRequest = HttpOpenRequest(hConnect,
				pszPostData ? "POST" : "GET",
				urlComponents.lpszUrlPath, HTTP_VERSION, NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_NO_COOKIES, 0);
			if (hRequest)
			{
				int nPostDataLen = pszPostData ? strlen(pszPostData) : 0;
				char szHeader[1024] = {0,}, *pReadBuf = NULL;
				DWORD dwInternetFlags, dwReadBufSize = 0, dwNumberOfBytesRead;
				
				dwInternetFlags = SECURITY_FLAG_IGNORE_UNKNOWN_CA
					| SECURITY_FLAG_IGNORE_REVOCATION
					| SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP
					| SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS
					| SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
					| SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
				bRet = InternetSetOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwInternetFlags, sizeof(dwInternetFlags));
				ASSERT(bRet);

				sprintf_s(szHeader, _countof(szHeader),
					"Accept: text/*\r\n"
					//"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*"
					//"Accept-Language: en-us"
					//"Accept-Encoding: gzip, deflate"
					"User-Agent: Mozilla/4.0 (compatible; MSIE 5.0;* Windows NT)\r\n"
					"Content-type: application/x-www-form-urlencoded\r\n"
					"Content-length: %d\r\n\n",
					nPostDataLen);
				bRet = HttpAddRequestHeaders(hRequest, szHeader, -1L, HTTP_ADDREQ_FLAG_ADD);
				ASSERT(bRet);

				if (pszPostData)
				{
					char *pszContentType = "Content-Type: application/x-www-form-urlencoded\r\n";
					bRet = HttpSendRequest(hRequest, pszContentType, strlen(pszContentType), (LPVOID)pszPostData, nPostDataLen);
				}
				else
				{
					bRet = HttpSendRequest(hRequest, NULL, 0, NULL, 0);
				}

				if (bRet)
				{
#ifdef	NO_USE_HttpQueryInfo
					string strBuf;
					dwReadBufSize = _countof(szHeader) - 1;
					while (InternetReadFile(hRequest, szHeader, dwReadBufSize, &dwNumberOfBytesRead) && (0 < dwNumberOfBytesRead))
					{
						szHeader[dwNumberOfBytesRead] = 0;
						strBuf += szHeader;
					}
					pReadBuf = (char *)malloc(strBuf.length() + 1);
					strcpy_s(pReadBuf, (strBuf.length() + 1), strBuf.c_str());
					pReadBuf[strBuf.length()] = 0;
#else
					dwNumberOfBytesRead = sizeof(dwReadBufSize);
					bRet = HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwReadBufSize, &dwNumberOfBytesRead, 0);
					DWORD dwErr = GetLastError();	// 12150 == ERROR_HTTP_HEADER_NOT_FOUND
					ASSERT(bRet);

					pReadBuf = (char *)malloc(dwReadBufSize + 1);
					memset(pReadBuf, 0, (dwReadBufSize + 1));
					bRet = InternetReadFile(hRequest, pReadBuf, dwReadBufSize, &dwNumberOfBytesRead);
					ASSERT(bRet);

					{
						int nReadBufLen = strlen(pReadBuf);
						char *pszReadBuf = (char *)malloc(nReadBufLen + 1);
						memset(pszReadBuf, 0, (nReadBufLen + 1));
						memcpy(pszReadBuf, pReadBuf, nReadBufLen);
						free(pReadBuf);
						pReadBuf = pszReadBuf;
					}
#endif
				}
				*pszOutBuffer = pReadBuf;

				InternetCloseHandle(hRequest);
			}
			else
			{
				//NULL == HINTERNET hRequest = HttpOpenRequest(hConnect, ...);
			}

			InternetCloseHandle(hConnect);
		}
		else
		{
			//NULL == HINTERNET hConnect = InternetConnect(hSession, ...);
		}

		InternetCloseHandle(hSession);
	}
	else
	{
		//NULL == HINTERNET hSession = InternetOpen("HTTPTEST", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	}

	return bRet;
}


void Cmimosav2clientDlg::httpPairedDevices()
{
	BOOL bRet = FALSE;
	int nCount = m_lbDevice.GetCount();
	CString strPostData;
	char *pRecvBuf = NULL;

	if (nCount)
	{
		CString strMacAddr, strMacAddrs, strText;
		CStringArray aryMacAddr;

		for (int i=0; i<nCount; i++)
		{
			m_lbDevice.GetText(i, strMacAddr);
			strText.Format("\"%s\",", strMacAddr);
			strMacAddrs += strText;

			aryMacAddr.Add(strMacAddr);
		}
		strMacAddrs = strMacAddrs.Left(strMacAddrs.GetLength() - 1);	// delete _T(',') end of string

		/*
		func_type=set_mac_address&op_tag={
		"acct_id":"0x0001",
		"mac":["A071A9BAABB6","A071A9BD2567"]
		}
		*/
		strPostData.Format(
			"func_type=set_mac_address&"
			"op_tag={"
			"\"acct_id\":\"%s\","
			"\"mac\":[%s]"
			"}",
			theApp.m_strUsername,
			strMacAddrs);
		bRet = HttpRequest((LPTSTR)(LPCTSTR)theApp.m_strHttpServer, (LPSTR)(LPCSTR)strPostData, &pRecvBuf);
		if (pRecvBuf)
		{
			/*<enc_result>
			<result>True</result>
			<error></error>
			<command>set_mac_address</command>
			<data><![CDATA[A071A9BAABB6=0001,A071A9BD2567=0002,A071A9BA9471=0003,A071A9BD258F=0004]]></data>
			</enc_result>*/
			CString strResult = pRecvBuf;
			int nStart = strResult.Find(_T("<data><![CDATA["));
			int nEnd = strResult.Find(_T("]]></data>"));
			if ((-1 < nStart) && (-1 < nEnd))
			{
				nStart += _tcslen(_T("<data><![CDATA["));
				strResult = strResult.Mid(nStart, (nEnd - nStart));

				/*A071A9BAABB6=0001,A071A9BD2567=0002,A071A9BA9471=0003,A071A9BD258F=0004*/
				if (aryMacAddr.GetCount())
				{
					CString strPhoneId;

					m_lbDevice.ResetContent();
					for (int i=0; i<aryMacAddr.GetCount(); i++)
					{
						strMacAddr = aryMacAddr.GetAt(i);
						if (-1 < (nStart = strResult.Find(strMacAddr)))
						{
							nStart += (strMacAddr.GetLength() + 1);	// '='
							if (-1 < (nEnd = strResult.Find(_T(','), nStart)))
								strPhoneId = strResult.Mid(nStart, (nEnd - nStart));
							else
								strPhoneId = strResult.Mid(nStart);

							strMacAddr = strPhoneId + _T('-') + strMacAddr;
							m_lbDevice.AddString(strMacAddr);
						}
					}
				}
			}
		}
	}

	logMsg(LOG_HTTP, "%d = httpPairedDevices(%s, %s)", bRet, strPostData, pRecvBuf);

	if (pRecvBuf)
		free(pRecvBuf);
}

void Cmimosav2clientDlg::httpCallTime(char *pszFromUser, int nHangupType, DWORD dwDuration_mSec)
{
	BOOL bRet = FALSE;
	CString strPostData;
	char *pRecvBuf = NULL;

	/*
	func_type=call_time&op_tag={
	"from_user":"jhlee",
	"hangup_type":"0001",
	"call_msec":"10000"
	}
	*/
	strPostData.Format(
		"func_type=call_time&"
		"op_tag={"
		"\"from_user\":\"%s\","
		"\"hangup_type\":\"%04d\","
		"\"call_msec\":\"%d\""
		"}",
		pszFromUser,
		nHangupType,
		dwDuration_mSec);
	bRet = HttpRequest((LPTSTR)(LPCTSTR)theApp.m_strHttpServer, (LPSTR)(LPCSTR)strPostData, &pRecvBuf);

	logMsg(LOG_HTTP, "%d = httpCallTime(%s, %s)", bRet, strPostData, pRecvBuf);

	if (pRecvBuf)
		free(pRecvBuf);
}
